package v1

import (
	v1 "gitee.com/youkelike/ziam/zapi/authz/v1"
	"gitee.com/youkelike/ziam/zsdk2/rest"
	"gitee.com/youkelike/ziam/zutils/runtime"
)

type AuthzV1Interface interface {
	RESTClient() rest.Interface
	Authz() AuthzInterface
	// AuthzGetter
}

// 只有 restclient 的构造方法会返回错误，所以要先实例化后存到字段，
type AuthzV1Client struct {
	restClient rest.Interface
}

func NewForConfig(c *rest.Config) (*AuthzV1Client, error) {
	// 跟服务相关的默认配置
	// 服务下的资源复用同一份配置，这里不用再做浅拷贝了
	SetConfigDefaults(c)

	// restclient 的构造方法会返回错误，所以要先实例化后存到字段，
	client, err := rest.RESTClientFor(c)
	if err != nil {
		return nil, err
	}

	return &AuthzV1Client{client}, nil
}

func NewForConfigOrDie(c *rest.Config) *AuthzV1Client {
	client, err := NewForConfig(c)
	if err != nil {
		panic(err)
	}

	return client
}

func New(c rest.Interface) *AuthzV1Client {
	return &AuthzV1Client{c}
}

func (c *AuthzV1Client) Authz() AuthzInterface {
	// 不会返回错误的子构造方法，不需要在自己的构造方法中调用并用字段来事先存储，
	return newAuthz(c)
}

func (c *AuthzV1Client) RESTClient() rest.Interface {
	if c == nil {
		return nil
	}

	return c.restClient
}

func SetConfigDefaults(c *rest.Config) {
	// 对配置文件中的部分选项进行个性化设置
	if c.GroupVersion == nil {
		gv := v1.SchemeGroupVersion
		c.GroupVersion = &gv
	}

	c.APIPath = ""
	c.Negotiator = runtime.NewSimpleClientNegotiator()

	if c.UserAgent == "" {
		c.UserAgent = rest.DefaultUserAgent()
	}
}
